﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity.Migrations;
using SQLStore;
using Models;
using System.Linq.Expressions;

namespace Services
{
    public class RelevanceServices : IDataAccess<Relevance>
    {
        CMSDBContext db;
        public RelevanceServices()
        {
            db = new CMSDBContext();
        }

        public RelevanceServices(string connectionString)
        {
            db = new CMSDBContext(connectionString);
        }

        public int Delete(object objValue)
        {
            Guid Id = Guid.Parse(objValue.ToString());
            var entity = db.Set<Relevance>().Where(t => t.Id == Id).FirstOrDefault();
            db.Set<Relevance>().Remove(entity);

            return Save();
        }

        public bool Exists(Expression<Func<Relevance, bool>> exp)
        {
            return db.Set<Relevance>().Any(exp);
        }

        public bool Exists(object objValue)
        {
            Guid Id = Guid.Parse(objValue.ToString());
            return db.Set<Relevance>().Any(t => t.Id == Id);
        }

        public Relevance GetByID(object objValue)
        {
            Guid Id = Guid.Parse(objValue.ToString());
            return db.Set<Relevance>().Where(t => t.Id == Id).FirstOrDefault();
        }

        public List<Relevance> GetList(Expression<Func<Relevance, bool>> exp)
        {
            return db.Set<Relevance>().Where(exp).ToList();
        }

        public int Save(Relevance entity)
        {
            if (!Exists(t => t.FirstId == entity.FirstId && t.SecondId == entity.SecondId && t.TableName == entity.TableName))
            {
                entity.Id = Guid.NewGuid();
                db.Set<Relevance>().AddOrUpdate(entity);
            }
            return Save();
        }
        int Save()
        {
            return db.SaveChanges();
        }
    }
}
